from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, ObjectProperty, StringProperty

import guiCommon
import world.wineTasting as wineTasting
from levinCommon import dateFromOrdinal
from kivy.clock import Clock 


class TastingLabel(guiCommon.CompactLabel):
    pass


class TastingEntryWid(BoxLayout):
    parentTastingList = None
    value = StringProperty("")
    attr  = StringProperty("")

    def __init__(self, parent,**args):
        self.parentTastingList = parent
        super(TastingEntryWid, self).__init__(**args)

    def on_height(self, *l):
        self.parentTastingList._trigger_height_calc()

class TastingWidgetButtons(guiCommon.LeVinButtonBar):    
    """A bar holding buttons for a single tasting : change mode, edit, suppress"""
    parentTastingList = None
    def __init__(self, parent,**args):
        self.parentTastingList = parent
        super(TastingWidgetButtons, self).__init__(**args)


class TastingWidget2(BoxLayout):
    """Displays the content of a single tasting. It's a  list of TastingEntryWid + a button bar.
    Number of TastingEntryWid varies according to basicMode. """

    tasting = ObjectProperty(None)
    entryWidList = []
    basicMode = BooleanProperty(True)

    basicModeByDefault = True

    numWidBasic = len(list(wineTasting.OrderedTastingAtt.iterBasicAtt()) ) +2
    numWidAdvanced = len(list(wineTasting.OrderedTastingAtt.iterAll()) ) +2

    is_selected = BooleanProperty(False)

    
    def __init__(self, **args):
        t= args.pop('tasting',None)
        super(TastingWidget2,self).__init__(**args)
        self._trigger_height_calc =  Clock.create_trigger(self._calculate_height, -1)
        self.on_basicMode(0, TastingWidget2.basicModeByDefault)
        
        if t:
            self.tasting = t
            
    def _calculate_height(self,*l):
        self.height = sum(c.height for c in self.children)

        
    def buildWidget(self):
        self.clear_widgets()
        numWid = self.numWidBasic if self.basicMode else self.numWidAdvanced
        widList = [ TastingEntryWid(self) for i in xrange(numWid) ] +[TastingWidgetButtons(self)]
        self.entryWidList = widList
        for w in widList:
            self.add_widget(w)

    def on_tasting(self, i, tasting ):
        widList = self.entryWidList
        w0 = widList[0]
        w0.attr = dateFromOrdinal(tasting.date)
        w0.value = str(tasting.rate)+'/10'
        
        for wid,  (att, v) in zip(widList[1:],self.wineTastingAtt()):
            wid.attr = v
            content = getattr(tasting,att)
            wid.value = content if content is not None else ''


    def on_basicMode(self, o, isBasic):
        if isBasic:
            self.wineTastingAtt = wineTasting.OrderedTastingAtt.iterBasicAtt
        else:
            self.wineTastingAtt = wineTasting.OrderedTastingAtt.iterAll
        self.buildWidget()
        if self.tasting :
            self.on_tasting(0, self.tasting)

    def advancedClicked(self):
        self.basicMode = not self.basicMode


from datetime import date as DateObj
            
class TastingDisplay(BoxLayout, guiCommon.BottleWidget):
    tastingList = ObjectProperty(None)
    buttonBar = ObjectProperty(None)
    def __init__(self,**kargs):
        super(TastingDisplay, self).__init__(**kargs)
        guiCommon.commonEvents.bind(on_tasting_edited = self.tasting_edited)
        guiCommon.commonEvents.bind(on_delete_tasting = self.delete_tasting)


    def delete_tasting(self, ev, tasting):
        bottle = tasting.bottle
        al = guiCommon.LeVinAlert( title=_('Suppress tasting from  %s'%(bottle.cru_name,)),
                         validText=_("Do suppress") ,
                         cancelText=_("Do NOT suppress"),
                         alertText= _('Please confirm suppression of tasting of a \n %s, %s'%(bottle.appellation, bottle.cru_name,)),                     
                         )
        al.cancelB.bind(on_release = al.dismiss)

        def _remove(*l):
            bottle.removeTasting(tasting)
            self.on_bottle(0,bottle)
            al.dismiss()
        al.validB.bind(on_release = _remove )


        al.open()
        

    def tasting_deleted(self, ev, tasting):
        if tasting.bottle is self.bottle:
            self.on_bottle(ev, tasting.bottle)
            
    def tasting_edited(self, ev, tasting):
        self.on_bottle(ev, tasting.bottle)
    

    def on_bottle(self, i, bottle):
        tastings = bottle.tastings

        adapter = self.tastingList.adapter
        if not tastings:            
            ntasting  = 0
            adapter.data = []
        else:
            ntasting  = len(tastings)
            adapter.data = list(reversed(tastings))
        nwidget = len(adapter.data)
        #print ' TASTING on_bottle ', i, unicode(bottle) , nwidget, ntasting       

        self.tastingList.children[0]._trigger_populate() # needed otherwise, nothing happen...

appComponents  = guiCommon.appComponents
def args_converter_default( i,t ):
    return {"tasting": t}
def args_converter_withTastingList( i,t ):
    return {"tasting": t, "is_selected": t is appComponents.tastingListWidget.selectedTasting}

class TListView(BoxLayout):
    adapter = ObjectProperty(None)
    def add_entry( self, n ):
        self.adapter.data.append( n )

    def nodes(self):
        return list(self.adapter.data)

    def setDebugPrefix(self,s):
        pass

    def select_node_at(self, row):
        
        pass

    def _trigger_height_calc(self,*l):
        pass
    
from kivy.factory import Factory
for cls in [TastingDisplay, TastingWidget2,  TListView]:
    Factory.register(cls.__name__, cls=cls)
from kivy.lang import Builder
guiCommon.load_kv_file('tastingDisplay.kv')

